<?php

namespace july\julyadmin\builder\forms;

use july\julyadmin\builder\FormBase;

/**
 * 表格组件
 */
class Items extends FormBase
{
    //h5组件type列表
    protected $h5_types = ['text', 'number', 'color', 'date', 'datetime-local', 'email', 'month', 'password', 'textarea', 'time', 'week', 'checkbox', 'select'];
    //items组件中的所有组件列表
    protected $items_forms = [];
    /**
     * 添加组件
     * @Author
     * @DateTime 2023-07-16T12:14:26+0800
     * @param    string                   $field 字段
     * @param    string                   $label 名称
     * @return this
     */
    public function __construct($field = '', $label = '')
    {
        $form                  = new \stdClass();
        $form->type            = 'items';
        $form->field           = $field;
        $form->label           = $label;
        $form->help            = '';
        $form->tips            = ['tips' => '', 'direction' => 2, 'time' => 0, 'background' => '#000000'];
        $form->required        = false;
        $form->show_rows_menus = true;
        $form->show_add_btn    = true;
        $form->show_delete_btn = true;
        $form->style           = '';
        $form->default         = [];

        //内容
        $form->value = [];
        $this->form  = $form;

        $this->js = '
        <script type="text/javascript" src="/static/assets/admin/js/fontIconPicker/jquery.fonticonpicker.min.js"></script>
        ';
        $this->css = '
        <link rel="stylesheet" type="text/css" href="/static/assets/admin/js/fontIconPicker/css/jquery.fonticonpicker.min.css">
        <link rel="stylesheet" type="text/css" href="/static/assets/admin/js/fontIconPicker/themes/bootstrap-theme/jquery.fonticonpicker.bootstrap.min.css" />
        ';
        return $this;
    }

    /**
     * 设置表格样式
     * @Author
     * @DateTime 2023-07-01T23:59:06+0800
     * @param    string                   $style 样式
     * @return this
     */
    public function style($style = '')
    {
        $this->form->style = $style;
        return $this;
    }

    /**
     * 是否显示表格行操作按钮
     * @Author
     * @DateTime 2023-07-02T00:04:20+0800
     * @param    boolean                  $show true，false
     * @return   this
     */
    public function showRowHandleMenus($show = true)
    {
        $this->form->show_rows_menus = $show;
        return $this;
    }

    /**
     * 是否显示表格行添加按钮
     * @Author
     * @DateTime 2023-07-02T00:05:51+0800
     * @param    boolean                  $show true，false
     * @return   this
     */
    public function addBtn($show = true)
    {
        $this->form->show_add_btn = $show;
        return $this;
    }

    /**
     * 是否显示表格行删除按钮
     * @Author
     * @DateTime 2023-07-02T00:05:51+0800
     * @param    boolean                  $show true，false
     * @return   this
     */
    public function deleteBtn($show = true)
    {
        $this->form->show_delete_btn = $show;
        return $this;
    }

    /**
     * 表格行
     * @Author
     * @DateTime 2023-07-16T12:12:45+0800
     * @param    Object                   $formObject 表格行中的每一个组件
     * @return   this
     */
    public function with($formObject)
    {
        if ($formObject instanceof \Closure) {
            $builder = new \july\julyadmin\builder\builder();
            $form    = new \july\julyadmin\builder\Form($builder);
            $formObject($form, []);
            if (count($form->forms)) {
                foreach ($form->forms as $form_key => $form_val) {
                    $form->forms[$form_key]->setColWidth(12)->size(0,12)->setItemsField($this->form->field)->isView($this->isView);
                }
                $this->items_forms = $form->forms;
            }
        }
        return $this;
    }

    /**
     * 渲染组件
     * @Author
     * @DateTime 2023-07-16T12:13:24+0800
     * @return   array
     */
    public function render()
    {
        $this->html        = '';
        $this->script      = '';
        $this->form->value = $this->form->default;
        if (isset($this->data[$this->form->field]) && $this->data[$this->form->field]) {
            if (!is_array($this->data[$this->form->field])) {
                throw new \Exception("items组件的value必须是数组！");
            }
            $this->form->value = $this->data[$this->form->field];
        }
        $required_html = $this->form->required && !$this->isView ? ' <font style="color:red;font-weight:bold;font-size:20px;vertical-align:-webkit-baseline-middle;">*</font>' : '';

        //处理tips
        $tips = '';
        if ($this->form->tips['tips']) {
            $tips = '<font class="form-tips-icon"><i class="mdi mdi-information-outline" tips="' . $this->form->tips['tips'] . '" direction="' . $this->form->tips['direction'] . '" time="' . $this->form->tips['time'] . '" background="' . $this->form->tips['background'] . '" onclick="showTips(this)"></i></font>';
        }

        $this->html .= <<< EOT

        <div class="row ps-0 pe-0 ms-0 me-0 mt-3 mb-3 col-md-{$this->colWidth}">
            <label class="col-sm-{$this->labelWidth} col-form-label pe-2 col-form-label-sm text-sm-end text-md-end text-lg-end text-xl-end">
                {$tips}{$this->form->label}
                {$required_html}
            </label>
EOT;
        $input_html = "";
        $disabled   = $this->readonly ? 'disabled' : '';
        //表头
        $header = '';
        if ($this->form->show_rows_menus && ($this->form->show_delete_btn || $this->form->show_add_btn) && !$this->isView) {
            $header .= "<th style='width:60px;text-align:center;'>操作</th>";
        }

        foreach ($this->items_forms as $fk => $fv) {
            $tips = '';
            if(isset($fv->form->tips)){
                //处理tips
                if ($fv->form->tips['tips']) {
                    $tips = '<font class="form-tips-icon"><i class="mdi mdi-information-outline" tips="' . $fv->form->tips['tips'] . '" direction="' . $fv->form->tips['direction'] . '" time="' . $fv->form->tips['time'] . '" background="' . $fv->form->tips['background'] . '" onclick="showTips(this)"></i></font>';
                }
            }
            
            $is_hidden = $fv->form->type == 'hidden' ? 'style="display:none;"' : '';
            $header .= "<th {$is_hidden}" . ($fv->items_title_style ? " style='{$fv->items_title_style}'" : "") . ">{$fv->form->label}{$tips}</th>";
        }
        //表格行
        $body = [];
        if ($this->form->show_rows_menus && !$this->isView) {
            if ($this->form->show_delete_btn) {
                $body[] = <<<EOT
            <td style="width:40px;">
                <button type="button" class="btn btn-danger mdi mdi-delete" title="删除" onclick="itemsDelete('form-{$this->form->field}',this)"></button>
            </td>
EOT;
            }

            if (!$this->form->show_delete_btn && $this->form->show_add_btn) {
                $body[] = <<<EOT
            <td style="width:40px;">

            </td>
EOT;
            }

        }

        //获取每个组件的html和js
        foreach ($this->items_forms as $fk => $fv) {
            $res = $fv->render($this->form->field);
            //把组件的label部分去掉
            $is_hidden   = $fv->form->type == 'hidden' ? 'style="display:none;"' : '';
            $res['html'] = preg_replace('/<label(.*?)col-form-label(.*?)<\/label>/si', "", $res["html"]);
            $body[]      = "<td {$is_hidden}>{$res['html']}{$res['script']}</td>";
        }
        if ($body) {
            $body = "<tr>" . implode('', $body) . "</tr>";
        } else {
            $body = "";
        }

        //footer
        $footer = '';
        if ($this->form->show_rows_menus && $this->form->show_add_btn && !$this->isView) {
            $colspan = 1;
            foreach ($this->items_forms as $fk => $fv) {
                if ($fv->form->type != 'hidden') {
                    $colspan++;
                }
            }
            $footer .= <<<EOT
            <tr>
                <td colspan="{$colspan}">
                    <button type="button" class="btn btn-success mdi mdi-clipboard-plus" title="新增" onclick="itemsAdd('form-{$this->form->field}')"></button>
                </td>
            </tr>
EOT;
        }

        //默认数据列表
        $values = [];
        foreach ($this->form->value as $data_k => $data_v) {
            $values_items = [];
            if ($this->form->show_rows_menus && !$this->isView) {
                if ($this->form->show_delete_btn) {
                    $values_items[] = <<<EOT
            <td style="width:40px;">
                <button type="button" class="btn btn-danger mdi mdi-delete" title="删除" onclick="itemsDelete('form-{$this->form->field}',this)"></button>
            </td>
EOT;
                }

                if (!$this->form->show_delete_btn && $this->form->show_add_btn) {
                    $values_items[] = <<<EOT
            <td style="width:40px;">

            </td>
EOT;
                }
            }
            foreach ($this->items_forms as $form_k => $form_v) {
                $res       = $form_v->setData($data_v)->render($this->form->field);
                $is_hidden = $form_v->form->type == 'hidden' ? 'style="display:none;"' : '';
                $content   = "<td" . ($form_v->form->type == 'hidden' ? ' style="display:none;"' : '') . " {$is_hidden}>{$res['html']}{$res['script']}</td>";
                $content   = preg_replace('/<label(.*?)col-form-label(.*?)<\/label>/si', "", $content);
                $content   = str_replace('_____items_row_id_____', '[' . $data_k . ']', $content);
                $content   = str_replace('_____items_row_fun_id_____', $data_k, $content);
                $content   = str_replace('_____items_row_prefix_____' . $form_v->form->field, $this->form->field . '[' . $data_k . '][' . $form_v->form->field . ']', $content);
                $preg      = "/(name=[\'\"]?)([^\'\"]*)([\'\"]?)/i";
                preg_match_all($preg, $content, $names);
                foreach ($names[2] as $nk => $nv) {
                    $preg = "/((_____items_row_prefix_____+)(.*+))/";
                    preg_match_all($preg, $nv, $nameres);
                    if (isset($nameres[3][0]) && $nameres[3][0]) {
                        if (isset($nameres[2][0]) && $nameres[2][0] == '_____items_row_id_____') {
                            $content = str_replace($nameres[2][0], '[' . $data_k . ']', $content);
                        }
                        if (isset($nameres[2][0]) && $nameres[2][0] == '_____items_row_fun_id_____') {
                            $content = str_replace($nameres[2][0], $data_k, $content);
                        }
                        if (isset($nameres[2][0]) && $nameres[2][0] == '_____items_row_prefix_____') {
                            $content = str_replace($nameres[2][0] . $nameres[3][0], $this->form->field . '[' . $data_k . '][' . $nameres[3][0] . ']', $content);
                        }
                    }
                }
                $values_items[] = $content;
            }
            if ($values_items) {
                $values[] = "<tr index='{$data_k}'>" . implode('', $values_items) . "</tr>";
            }
        }
        if ($values) {
            $values = implode('', $values);
        } else {
            $values = "";
        }

        $input_html .= <<<EOT
            <table id="form-{$this->form->field}-body-template" style="display:none;">
                <tbody>
                    {$body}
                </tbody>
            </table>

            <table id="form-{$this->form->field}" name="{$this->form->field}" class="table table-hover table-bordered" style="{$this->form->style}">
                <thead>
                    {$header}
                </thead>
                <tbody>
                    {$values}
                </tbody>
                <tfoot>
                    {$footer}
                </tfoot>
            </table>
EOT;
        
        //处理help
        if ($this->form->help) {
            $input_html .= <<<EOT

            <div class="form-help form-text">
                <i class="mdi mdi-information-outline"></i>
                <font>{$this->form->help}</font>
            </div>
EOT;
        }

        $this->html .= <<< EOT

            <div class="col-sm-{$this->inputWidth}" style="overflow-x:scroll;">
                {$input_html}
            </div>
        </div>
EOT;
        if (!$this->readonly) {
            $this->script .= <<<EOT

            <script type="text/javascript">
                var body_templete = '';
                $(document).ready(function(){
                    body_templete = $('#form-{$this->form->field}-body-template tbody').html();
                    $('#form-{$this->form->field}-body-template tbody').remove();
                });

                function itemsAdd(table_id){
                    var tr_length = $('#'+table_id +' tbody tr').length;
                    var index = -1;
                    if(tr_length==0){
                        index = tr_length;
                    }else if(tr_length>0){
                        var index = $('#'+table_id +' tbody tr').eq(tr_length-1).attr('index');
                        if(index==undefined || index==''){
                            for(var i=0;i<tr_length;i++){
                                temp_index = $('#'+table_id +' tbody tr').eq(tr_length-(i+1)).attr('index');
                                if(temp_index!=undefined && temp_index!='' && (index==undefined || index=='')){
                                    index = parseInt(temp_index)+1;
                                }
                            }
                        }else{
                            index = parseInt(index)+1;
                        }
                    }
                    body = body_templete.replaceAll('_____items_row_id_____','['+index+']');
                    body = body.replaceAll('_____items_row_fun_id_____',index);
                    //把name替换成新的
                    var srcReg = /(name=[\'\"]?)([^\'\"]*)([\'\"]?)/ig;
                    var r = body.match(srcReg);
                    for(var i=0;i<r.length;i++){
                        var field = r[i].replaceAll('name=\"','');
                        field = field.replaceAll('\"','');
                        field = field.split('_____items_row_prefix_____')[1];
                        var fieldstr = field.match(/[a-zA-Z_\-0-9]+/);
                        var newfield = field.replace(fieldstr[0],'['+fieldstr[0]+']');
                        body = body.replaceAll('_____items_row_prefix_____'+field,'{$this->form->field}'+'['+index+']'+newfield);
                    }

                    $('#'+table_id +' tbody').append(body);
                    setTimeout(function(){
                        tr_length = $('#'+table_id +' tbody tr').length;
                        $('#'+table_id +' tbody tr').eq(tr_length-1).attr('index',index);
                        $('#'+table_id +' tbody tr td').eq(tr_length-1).attr('index','_'+index);
                    },100);
                }

                function itemsDelete(table_id,that){
                    $(that).parent().parent().remove();
                }
            </script>

EOT;

        }
        $result = ['html' => $this->html, 'script' => $this->script, 'js' => $this->js, 'css' => $this->css];
        return $result;
    }
}
